<html>
<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<head>
<title>Section 5.2.&nbsp; Defining Functions</title>
<link rel="STYLESHEET" type="text/css" href="images/style.css">
<link rel="STYLESHEET" type="text/css" href="images/docsafari.css">
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-5-SECT-1.html><img src="images/prev.gif" width="60" height="17" border="0" align="absmiddle" alt="Previous Page"></a>
<td align="right"><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-5-SECT-3.html><img src="images/next.gif" width="60" height="17" border="0" align="absmiddle" alt="Next Page"></a>
</div></td></tr></table>
<br><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td valign="top"><a name="learnphpmysql-CHP-5-SECT-2"></a>
<h3 id="title-IDAYY3EF" class="docSection1Title">5.2. Defining Functions</h3>
<a name="IDX-CHP-5-0173"></a> 
<a name="IDX-CHP-5-0174"></a> 

<p class="docText">There are already many functions built into PHP. However, you can define your own and organize your code into functions. To define your own functions, start out with the <tt>function</tt> statement:</p>
<pre>
function <tt><i>some_function</i></tt>([<tt><i>arguments</i></tt>]) { <tt><i>code to execute</i></tt> }
</pre><br>

<p class="docText">The brackets (<tt>[ ]</tt>) mean optional. The code could also be written with <tt><i>optional_arguments</i></tt> in place of <tt>[</tt><tt><I>arguments</i></tt><tt>]</tt>. The <tt>function</tt> keyword is followed by the name of the function. Function names abide by the same rules as other named objects such as variables in PHP. A pair of parentheses must come next. If your function has parameters, they're specified within the parentheses. Finally, the code to execute is listed between curly brackets, as seen in the code above.</p>
<p class="docText">You can define functions anywhere in your code and call them from virtually anywhere. Scope rules apply. The scope of a variable is the context within which it's defined. For the most part, all PHP variables have only a single scope. A single scope spans included and required files as well. The function is defined on the same page or included in an include file. Functions can have parameters and return values that allow you to reuse code.</P>
<p class="docText">To create your own function that simply displays a different hello message, you would write:</P>
<pre>
&lt;?php
<span class="docEmphStrong">function hi()</span>
<span class="docEmphStrong">{</span>
  <span class="docEmphStrong">echo ("Hello from function-land!");</span>
<span class="docEmphStrong">}</span>
//Call the function
hi();
?&gt;
</pre><br>

<p class="docText">which displays:</P>
<pre>
Hello from function-land!
</pre><br>

<p class="docText">The <tt>hi</tt> function doesn't take any parameters, so you don't list anything between the parentheses. Now that you've defined a simple function, let's mix in some parameters.</p>
<a name="learnphpmysql-CHP-5-SECT-2.1"></a>
<h4 id="title-IDAC13EF" class="docSection2Title">5.2.1. Parameters</H4>
<p class="docText">Parameters provide a convenient way to pass information to a function when you call it without having to worry about variable scope. In PHP, you don't have to define what type of data a parameter holdsonly the name and number of parameters<a name="IDX-CHP-5-0175"></a> 
 must be specified.</p>
<p class="docText">An example of a function is <tt>strtolower</tt>, which converts your string "Hello world!" to lowercase. It takes a parameter of the type string, which is a data type (described in a previous chapter). There's also another function <tt>strtoupper</tt> that converts all characters of your string into uppercase letters, as shown in <a class="docLink" href="#learnphpmysql-CHP-5-EX-4">Example 5-4</a>.</p>
<a name="learnphpmysql-CHP-5-EX-4"></a><H5 id="title-IDA213EF" class="docExampleTitle">Example 5-4. Using the string capitalization functions</h5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><TR><td>

<a name="IDX-CHP-5-0176"></a> 

<pre>
&lt;?php
// Capitalize a string
function capitalize( $str )
{
  // First, convert all characters to lower case
  $str = strtolower($str);
  // Second, convert the first character to upper case
  $str{0} = strtoupper($str{0});
  echo $str;
}
capitalize("hEllo WoRld!" );

?&gt;
</pre><br>

</td></tr></table></P>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-5-EX-4">Example 5-4</a> outputs:</P>
<pre>
Hello world!
</pre><br>

<p class="docText">The value of <tt>$str</tt> was echoed inside the function, because you didn't specify any way to get the value out of the function.</p>
<p><table border="0" bgcolor="black" cellspacing="0" cellpadding="1" width="90%" align="center"><tr><TD><table bgcolor="white" width="100%" border="0" cellspacing="0" cellpadding="6"><tr><TD width="60" valign="top"><img src="images/tip_yellow.jpg" width="50" height="54" alt=""></td><TD valign="top">
<p class="docText">PHP also doesn't require definition of whether a function actually returns a value, or what data type it returns.</P>
</TD></tr></table></td></tr></table></p><br>
<p class="docText">Parameters can also contain default values. With a default value, you actually don't need to pass the function any input for it to set the default. Let's change your <tt>capitalize</tt> function to have a default value that allows you to capitalize the first letter of each word or just the sentence; see <a class="docLink" href="#learnphpmysql-CHP-5-EX-5">Example 5-5</a>.</p>
<a name="learnphpmysql-CHP-5-EX-5"></a><h5 id="title-IDAJ33EF" class="docExampleTitle">Example 5-5. Creating a capitalize function with a default parameter $each</h5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><td>

<pre>
&lt;?php
// Capitalize a string or the first letter of each word
function capitalize( $str, $each=TRUE )
{
  // First, convert all characters to lower case
  $str = strtolower($str);
  if ($each === TRUE) {
     $str = ucwords ($str);
  } else {
     $str = strtoupper($str);
  }
  echo ("$str &lt;br&gt;");
}
capitalize("hEllo WoRld!");
echo ("Now do the same with the echo parameter set to FALSE.&lt;br&gt;");
capitalize("hEllo WoRld!",FALSE);
?&gt;
</pre><br>

</td></tr></table></P>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-5-EX-5">Example 5-5</a> produces:</p>
<pre>
Hello World!
Now do the same with the echo parameter set to FALSE.
HELLO WORLD!
</pre><br>

<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-5-EX-5">Example 5-5</a> shows that when you execute <tt>capitalize</tt> with just one parameter, <tt>hEllo WoRld!, $each</tt> takes on the default value of <tt>TRUE</tt>. Therefore, only the first letter of each word gets capitalized. When the second execution of <tt>capitalize</tt> sends in a value of <tt>FALSE</tt> from the parameter, <tt>$each</tt> becomes <tt>FALSE</tt> in the function and the output changes. Also, <tt>ucwords</tt> changes the first character of a string to uppercase.</P>

<a name="learnphpmysql-CHP-5-SECT-2.2"></a>
<h4 id="title-IDAT43EF" class="docSection2Title">5.2.2. Parameter References</H4>
<p class="docText">When you pass an argument to the function, a local copy is made in the function to store the value. Any changes made to that value don't affect the source of the parameter. You can define parameters that modify the source variable by defining reference parameters.<a name="IDX-CHP-5-0177"></a> 
<a name="IDX-CHP-5-0178"></a> 
<a name="IDX-CHP-5-0179"></a> 
</p>
<p class="docText"><span class="docEmphasis">Reference parameters</span> define references by placing an ampersand (<tt>&amp;</tt>) directly before the parameter in the functions definition.</p>
<p class="docText">Let's modify the <tt>capitalize</tt> function from <a class="docLink" href="#learnphpmysql-CHP-5-EX-5">Example 5-5</a> to take a reference variable for the string to <tt>capitalize</tt> (<a class="docLink" href="#learnphpmysql-CHP-5-EX-6">Example 5-6</a>).</p>
<a name="learnphpmysql-CHP-5-EX-6"></a><H5 id="title-IDAGIVVF" class="docExampleTitle">Example 5-6. Modifying capitalize to take a reference parameter</h5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><TR><td>

<pre>
&lt;?php
function capitalize( &amp;$str, $each=true )
{
    // First, convert all characters to lower case
    $str = strtolower($str);
   if ($each === true) {
      $str = ucwords($str);
   } else {
      $str{0} = strtoupper($str{0});
   }
}
$str = "hEllo WoRld!";
capitalize( &amp;$str );
echo $str;
?&gt;
</pre><br>

</TD></tr></table></p>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-5-EX-6">Example 5-6</a> returns:</p>
<pre>
Hello World!
</pre><br>

<p class="docText">Because <tt>capitalize</tt> defined the <tt>$str</tt> parameter as a reference parameter, a link to the source variable was sent to the function when it was executed. The function essentially accessed and modified the source variable. Had the variable not been declared as a reference, the original value of <tt>"hEllo WoRld!"</tt> would display.</P>

<a name="learnphpmysql-CHP-5-SECT-2.3"></a>
<H4 id="title-IDACJVVF" class="docSection2Title">5.2.3. Including and Requiring PHP Files</h4>
<a name="IDX-CHP-5-0180"></a> 
<a name="IDX-CHP-5-0181"></a> 
<a name="IDX-CHP-5-0182"></a> 
<a name="IDX-CHP-5-0183"></a> 

<p class="docText">To make your code more readable, you can place your functions in a separate file. Many PHP add-ons that you download off the Internet contain functions already placed into files that you simply include<a name="IDX-CHP-5-0184"></a> 
 in your PHP program. However, PHP provides four functions that enable you to insert code from other files.</p>
<ul><li><p class="docList"><tt>include</tt></P></li><LI><p class="docList"><tt>require</tt></p></LI><LI><p class="docList"><tt>include_once</tt></P></li><li><p class="docList"><tt>require_once</tt></p></li></ul>
<p class="docText">All the <tt>include</tt> and <tt>require</tt> functions can take a local file or URL as input, but they cannot import a remote file. <tt>require</tt> and <tt>include</tt> functions are pretty similar in their functionality except for the way in which they handle an irretrievable resource. For example, <tt>include</tt> and <tt>include_once</tt> provide a warning if the resource cannot be retrieved and try to continue execution of the program. The <tt>require</tt> and <tt>require_once</tt> functions provide stop processing of the particular page if they can't retrieve the resource. Now we're going to get more specific about these four functions.</p>

<a name="learnphpmysql-CHP-5-SECT-2.4"></a>
<h4 id="title-IDANLVVF" class="docSection2Title">5.2.4. The include Statement</h4>
<p class="docText">The <tt>include</tt> statement allows you to include and attach other PHP scripts to your own script. You can think of it as simply taking the included file and inserting them into your PHP file. <a class="docLink" href="#learnphpmysql-CHP-5-EX-7">Example 5-7</a> is called <span class="docEmphasis">add.php</span>.</p>
<a name="learnphpmysql-CHP-5-EX-7"></a><h5 id="title-IDA5LVVF" class="docExampleTitle">Example 5-7. A sample include file called add.php</h5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><td>

<pre>
&lt;?php
function add( $x, $y )
{
  return $x + $y;
}
?&gt;
</pre><BR>

</td></tr></table></P>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-5-EX-8">Example 5-8</a> assumes that <span class="docEmphasis">add.php</span> is in the same directory as the <tt>include</tt> function.</P>
<a name="learnphpmysql-CHP-5-EX-8"></a><h5 id="title-IDATMVVF" class="docExampleTitle">Example 5-8. Using the include function</H5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><td>

<pre>
&lt;?php
include('add.php');
echo add(2, 2);
?&gt;
</pre><BR>

</td></tr></table></P>
<p class="docText">When executed, this produces:</p>
<pre>
4
</pre><br>

<p class="docText">As seen in <a class="docLink" href="#learnphpmysql-CHP-5-EX-8">Example 5-8</a>, the <tt>include</tt> statement attaches other PHP scripts so that you can access other variables, functions, and classes.</P>
<p><table border="0" bgcolor="black" cellspacing="0" cellpadding="1" width="90%" align="center"><tr><td><table bgcolor="white" width="100%" border="0" cellspacing="0" cellpadding="6"><tr><TD width="60" valign="top"><img src="images/warning_yellow.jpg" width="51" height="36" alt=""></TD><td valign="top">
<p class="docText">You can name your include files anything that you like, but you should always use the <span class="docEmphasis">.php</span> extension, because if you name them something else, such as <span class="docEmphasis">.inc</span>, it's possible that a user can request the <span class="docEmphasis">.inc</span> file and that the web server will return the code stored in it. This is a security risk, as it may reveal passwords or details about how your program works that can reveal weaknesses in your code. This is because PHP files are parsed by the PHP interpreter.</p>
</td></tr></table></TD></tr></table></P><br>
<a name="learnphpmysql-CHP-5-SECT-2.4.1"></a>
<H5 id="title-IDAYNVVF" class="docSection3Title">5.2.4.1. The include_once statement</H5>
<a name="IDX-CHP-5-0185"></a> 
<a name="IDX-CHP-5-0186"></a> 
<a name="IDX-CHP-5-0187"></a> 

<p class="docText">A problem may arise when you include many nested PHP scripts, because the <tt>include</tt> statement doesn't check for scripts that have already been included.</P>
<p class="docText">For example, if you did this:</p>
<pre>
&lt;?php
<span class="docEmphStrong">include('add.php');</span>
<span class="docEmphStrong">include('add.php');</span>
echo add(2, 2);
?&gt;
</pre><br>

<p class="docText">You'd get this error:</p>
<pre>
<b>Fatal error:</b> Cannot redeclare add() (previously declared in
/home/www/htmlkb/oreilly/ch5/add.php:2) in
<b>/home/www/htmlkb/oreilly/ch5/add.php</b> on line <b>2</b>
</pre><br>

<p class="docText">The above directory may not be where your file is located; your file will go wherever you've designated a place for it. To avoid this type of error, you should use the <tt>include_once</tt> statement.</p>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-5-EX-9">Example 5-9</a> shows the <tt>include_once</tt> statement.</p>
<a name="learnphpmysql-CHP-5-EX-9"></a><h5 id="title-IDA0PVVF" class="docExampleTitle">Example 5-9. Using include_once to include a file</h5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><td>

<pre>
&lt;?php
<span class="docEmphStrong">include_once('add.php');</span>
<span class="docEmphStrong">include_once('add.php');</span>
echo add(2, 2);
?&gt;
</pre><BR>

</td></tr></table></P>
<p class="docText">This outputs the following when executed:</P>
<pre>
4
</pre><br>

<p class="docText">Obviously, you're not going to place the same <tt>include</tt> statements right next to each other, but it's far more likely that you may include a file, which includes another file you've already included. You should always use <tt>include_once</tt>, as there really isn't any drawback to using it instead of <tt>include</tt>.</P>
<p class="docText">There are a couple of problems to look out for when using <tt>include</tt> or <tt>include_once</tt> that can prevent the code from being included. If the file has been deleted, obviously, PHP can't include it. The other problem is if the <tt>include</tt> statement is accidentally deleted from the PHP page. This can happen if the <tt>include</tt> statement isn't obviously related to the code that uses it and nearby the code in the file. One way to prevent this problem is to place the code that uses the included code in a function that's defined next to the <tt>include</tt> statement. Then place a call to the function where you need to use the code in your main PHP code. Additionally, you could use <tt>include_once</tt> at the beginning of the function definition, making it very clear that the code needs the included file.</p>
<p class="docText">As demonstrated in the above two paragraphs, there are many potential solutions to numerous problems you may run into while creating functions and scripts. Keep in mind that coding is an iterative process, and, as we'll discuss in <a class="docLink" href="learnphpmysql-CHP-15.html#learnphpmysql-CHP-15">Chapter 15</a>, you can use all the resources available on the Internet from other PHP programmers to help you work through any code issues and problems you may have while coding. The PHP community is available to help with all issues, and usually gets back to a posting board quicker than it might take you to sort out your problem!</p>

<a name="learnphpmysql-CHP-5-SECT-2.4.2"></a>
<h5 id="title-IDAVRVVF" class="docSection3Title">5.2.4.2. require and require_once functions</H5>
<a name="IDX-CHP-5-0188"></a> 
<a name="IDX-CHP-5-0189"></a> 
<a name="IDX-CHP-5-0190"></a> 
<a name="IDX-CHP-5-0191"></a> 
<a name="IDX-CHP-5-0192"></a> 
<a name="IDX-CHP-5-0193"></a> 
<a name="IDX-CHP-5-0194"></a> 
<a name="IDX-CHP-5-0195"></a> 
<a name="IDX-CHP-5-0196"></a> 
<a name="IDX-CHP-5-0197"></a> 

<p class="docText">To make sure that a file is included and to stop your program, immediately use <tt>require</tt> and its counter part, <tt>require_once</tt>. These are exactly the same as <tt>include</tt> and <tt>include_once</tt> except that they make sure that the file is present; otherwise, the PHP script's execution is halted, which wouldn't be a good thing! Examples of when you should use <tt>require</tt> instead of <tt>include</tt> are if the file you're including defines critical functions that your script won't be able to execute or variable definitions such as database connection details.</p>
<p class="docText">For example, if you attempt to require a file that doesn't exist:</p>
<pre>
&lt;?php
<span class="docEmphStrong">require_once('add_wrong.php');</span>
echo add(2, 2);
?&gt;
</pre><BR>

<p class="docText">you'd get this error:</p>
<pre>
<b>Warning:</b> main(add_wrong.php): failed to open stream: No such
file or directory in
<B>/home/www/htmlkb/oreilly/ch5/require_once.php on line</b> 2

<b>Fatal error: main():</b> Failed opening required 'add_wrong.php'
(include_path='.:/usr/share/php:/usr/share/pear') in
<b>/home/www/htmlkb/oreilly/ch5/require_once.php</b> on line 2
</pre><br>

<p class="docText">All file paths are contingent on where your files are located. The last topic we'll cover with functions is how to test whether a function has been defined before attempting to use it.</p>


<a name="learnphpmysql-CHP-5-SECT-2.5"></a>
<H4 id="title-IDAYUVVF" class="docSection2Title">5.2.5. Testing a Function</H4>
<a name="IDX-CHP-5-0198"></a> 
<a name="IDX-CHP-5-0199"></a> 

<p class="docText">If compatibility with various PHP versions is especially important to your script, it's useful to be able to check for the existence of functions. The function <tt>function_exists</tt> does just what you'd expect. It takes a string with a function's name and returns <tt>trUE</tt> or <tt>FALSE</tt> depending on whether the function has been defined. For example:</p>
<pre>
&lt;?php
$test=function_exists("test_this");
if ($test==TRUE)
{ echo "Function test_this exists.";
}
else
{
  echo "Function test_this does not exist.";
//call_different_function();
}
?&gt;
</pre><br>

<p class="docText">displays:</p>
<pre>
Function test_this does not exist.
</pre><BR>

<p class="docText">The "Function test_this does not exist" message displays because you haven't defined the function <tt>test_this</tt>, therefore the program code either displays an error message in plain English or attempts to use a different function.</p>
<p class="docText">You've learned how to define functions and their parameters, and how to pass information back and forth from them, plus we've given you some good examples of how to troubleshoot potential function problems.</P>
<p class="docText">Next, we'll introduce an alternate style of programming called Object-Orientated (OO) programming. PHP 4.1 had minimal support for OO programming, but with the introduction of 5.0, OO is fully developed. There is continuous debate about which type of coding is better, and really, neither is better or worse than the other; it's mostly a style issue and personal preference.</p>


<a href="11011536.html"><img src="images/pixel.jpg" alt="" width="1" height="1" border="0"></a></TD></TR></table>
<br>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-5-SECT-1.html><img src="images/prev.gif" width="60" height="17" border="0" align="absmiddle" alt="Previous Page"></a>
<td align="right"><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-5-SECT-3.html><img src="images/next.gif" width="60" height="17" border="0" align="absmiddle" alt="Next Page"></a>
</div></td></tr></table>
<script type="text/javascript"><!--
google_ad_client = "pub-0203281046321155";
google_alternate_ad_url = "http://www.bookhtml.com/adbrite.htm";
google_ad_width = 728;
google_ad_height = 90;
google_ad_format = "728x90_as";
google_ad_type = "text_image";
google_ad_channel ="4867465545";
google_color_border = "FFFFFF";
google_color_link = "0000FF";
google_color_bg = "FFFFFF";
google_color_text = "000000";
google_color_url = "0000FF";
//--></script>
<script type="text/javascript"
  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</html>
